package com.cet.test.mt04.qz2;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: cet-practice
 * @description:
 * @author: 陈恩涛
 * @create: 2023-05-06 20:02
 **/
public class Client {

    public static void main(String[] args) {

        AService aService = new AService();
        BService bService = new BService();
        CService cService = new CService();

        ExecutorService executorService = Executors.newCachedThreadPool();

        CompletableFuture<Integer> cf1 = CompletableFuture.supplyAsync(aService::get, executorService);
        CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(bService::get, executorService);
        CompletableFuture<Integer> cf3 = CompletableFuture.supplyAsync(cService::get, executorService);

        List<CompletableFuture<Integer>> cfList = Arrays.asList(cf1, cf2, cf3);

        CompletableFuture
            .allOf(cfList.toArray(new CompletableFuture[cfList.size()]))
            .whenComplete((v,e) -> {
                if (e == null) {
                    Optional<Integer> reduce = cfList
                        .stream()
                        .map(CompletableFuture::join)
                        .reduce(Integer::sum);
                    reduce.ifPresent(System.out::println);
                }
            });

        executorService.shutdown();
    }
}
